package cn.com.visionsky.bocsz.bda.webservice.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 46043 on 2016/10/28.
 */
public class StableControlFilter implements Filter {

    private static final Logger logger = LoggerFactory
            .getLogger(StableControlFilter.class);

    private Integer maxWsConnectCount = 500;

    private AtomicInteger count = new AtomicInteger();

    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info(String.format("maxWsConnectCount is %d.", maxWsConnectCount));
    }

    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) {
        boolean entry = isEntry();
        if (entry) {
            try {
                count.incrementAndGet();
                logger.info(String.format("maxWsConnectCount is %d, now is %d."
                        , maxWsConnectCount, count.intValue()));
                chain.doFilter(request, response);
            } catch (ServletException e) {
                logger.error("ServletException", e);
            } catch (IOException e) {
                logger.error("IOException", e);
            } finally {
                count.decrementAndGet();
            }
        }
        return;
    }

    public void destroy() {

    }

    private boolean isEntry() {
        if (count.intValue() > new AtomicInteger(500).intValue()) {
            return false;
        }
        return true;
    }
}
